# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import requests
import json
import serial
import time

rhbase = [20,20,21,21,22,22,23,23,24,24,
          25,25,26,26,27,27,28,28,29,29,
          30,30,31,31,32,32,33,33,34,34,
          35,35,36]
rhdata = [1030,1027,1025,1023,1020,1017,1015,1013,1010,1007,
         1005,1003,1000,997,995,993,990,987,985,983,
         980,977,975,973,970,967,965,963,960,957,
         955,953,950]
equipment_status = {}
local_storage = {}
# 485
ser1 = serial.Serial("/dev/ttyUSB1", 9600, timeout=0.01)  # receive data once every 0.01S 
ser1.flushInput()
# zigbee
ser = serial.Serial("/dev/ttyUSB0", 9600, timeout=0.01)  # receive data once every 0.01S 
ser.flushInput()

def send_device(index:int):
    printData = bytearray()
    #0xaa
    printData.append(170)
    #0x55
    printData.append(85)

    tmp_data=equipment_status[index]
    #选择模式：手动/自动
    printData.append(tmp_data[2]+1)
    #选择设备
    printData.append(index)
    #设定数值
    Data3 = tmp_data[0]
    printData.append(Data3//10)
    printData.append(Data3%10)
    # revise
    printData.append(tmp_d
    Data4 = tmp_data[3]
    printData.append(Data4//10)
    printData.append(Data4%10)
    print(printData)
    ser1.write(printData)
    ser1.flush()

def parse_json(json_str: str):
    info_dict = json.loads(json_str)
    data_list = info_dict["data"]
    for item in data_list:
        tmp_list = [item["value"], item["revise"], item["limit"],item["time"]]
        equipment_status[item["id"]] = tmp_list


def cmp_local_origin(index_compare: int) -> bool:
    if index_compare not in local_storage.keys():
        return False
    local_list = local_storage[index_compare]
    origin_list = equipment_status[index_compare]
    if len(local_list) != len(origin_list):
        return False
    for i in range(len(local_list)):
        if local_list[i] != origin_list[i]:
            return False
    return True


def merge_origin_local(index_change: int):
    local_storage[index_change] = equipment_status[index_change]
    return


def postData(Rt, Rop, Hum):
    url = "http://192.168.253.1:7550/api/raspberry"

    payload = json.dumps({
        "illumination": Rop,
        "temperature": Rt,
        "humidity": Hum
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    print(response.text)

    return response.text


def dataGet():
    dataList = []
    
    # print(ser.portstr)
    data = ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
    while ser.inWaiting() > 0:
        data = ser.readline()
        # print(234)
    # print(len(data))
    if data != "":
        if len(data) == 8:
            if data[0] == 170:
                result_data=int(data[3])*1000+int(data[4])*100+int(data[5])*10+int(data[6])
                print("设备--1--温度值：%d,光照值：%d,湿度值：%d" % (int(data[1]),int(data[2]),result_data))
                dataList.append(postData(str(int(data[1])), str(int(data[2])),str(result_data)))
            if data[0] == 187:
                result_data=int(data[3])*1000+int(data[4])*100+int(data[5])*10+int(data[6])
                print("设备--2--温度值：%d,光照值：%d,湿度值：%d" % (int(data[1]), int(data[2]),result_data))
                dataList.append(postData(str(int(data[1])), str(int(data[2])), str(result_data)))
    return dataList

if __name__ == '__main__':
    print("You can always receive data, press Ctrl + C to exit")
    while 1:
        data_resopnse=dataGet()
        # print(data_resopnse)
        for item in data_resopnse:
            parse_json(item)
            for index_compare in equipment_status.keys():
                if not cmp_local_origin(index_compare):
                    # TODO 添加发送代码
                    send_device(index_compare)
                    merge_origin_local(index_compare)
